package com.diaohw.module.websocket.service.ws.handle;

import com.diaohw.module.websocket.obj.dto.MsgDTO;
import com.diaohw.module.websocket.obj.vo.MsgVO;
import com.diaohw.module.websocket.properties.WsMessageProperties;
import com.diaohw.module.websocket.service.MsgService;
import com.diaohw.platform.common.util.JsonUtil;
import com.diaohw.platform.utility.netty.NettyServerUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author 刁海文
 * @since 2024/4/17 20:48
 */
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<String> implements CommandLineRunner {

    @Resource
    private MsgService service;
    @Resource
    private WsMessageProperties properties;

    @Override
    public void run(String... args) throws Exception {
        NettyServerUtils.start(properties.getNettyPort(), this);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        MsgDTO object = JsonUtil.toBean(msg, MsgDTO.class);
        MsgVO send = service.send(object);
        if (object.isCallback()) {
            ByteBuf byteBuf = Unpooled.copiedBuffer(JsonUtil.toJsonString(send), CharsetUtil.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }
    }
}
